<template>
    <div class="add">
        <SavePage title="新建缺陷">
            <template slot="buttons">
                <BaseButton :loading="submitLoading" @click="submit()">保存</BaseButton>
            </template>
            <template slot="body">
                <el-form ref="refForm" size="medium" label-width="120px" :model="form" :rules="rules">
                    <BaseInfo ref="baseInfo" :form.sync="form" @locationTypeChange="locationTypeChange"></BaseInfo>
                    <el-row v-if="form.locationType === 4">
                        <el-col>
                            <el-form-item label="设备信息" prop="deviceInfo">
                                <BaseButton type="text" @click="addDeviceInfo">选择设备</BaseButton>
                                <BaseButton type="text" :disabled="!form.deviceInfo.length" @click="handleDeleteDevice(null)">批量移除</BaseButton>
                            </el-form-item>
                            <BaseTable
                                v-if="form.deviceInfo && form.deviceInfo.length > 0"
                                :columns="columns"
                                :data="form.deviceInfo"
                                max-height="500px"
                                highlight-current-row
                                @selection-change="handleSelectionChange"
                            >
                                <template #result="{ scope: { row } }">
                                    <el-select v-model="row.inspectionResult" clearable placeholder="请选择" style="width: 100%">
                                        <el-option v-for="item in devResults" :key="item.value" :label="item.label" :value="item.value" />
                                    </el-select>
                                </template>
                                <template #remake="{ scope: { row } }">
                                    <el-input v-model.trim="row.reason" placeholder="请输入，200字以内" maxlength="200" size="mini" type="table" />
                                </template>
                                <template #handle="{ scope: { row } }">
                                    <BaseButton type="text" color="danger" @click="handleDeleteDevice(row)"> 移除 </BaseButton>
                                </template>
                            </BaseTable>
                        </el-col>
                    </el-row>
                </el-form>
            </template>
        </SavePage>
        <!-- 选择设备弹框表格 -->
        <el-dialog width="860px" :visible.sync="deviceDialogVisible" title="选择设备">
            <DeviceDialog
                :visible="deviceDialogVisible"
                :params="{ highwayCode: form.highwayCode }"
                :highway-code="form.highwayCode"
                @close="deviceDialogVisible = false"
                @get-list="getDeviceList"
            />
        </el-dialog>
    </div>
</template>
<script>
import BaseInfo from './baseInfo.vue'
import reconfirm from '@/utils/reconfirm'
import { InspectionDefectRecordModel } from '@/models'
import useSuccess from '@/hooks/useSuccess'
import { devResults } from '../../../constants'
export default {
    components: {
        BaseInfo
    },
    data() {
        return {
            model: new InspectionDefectRecordModel(),
            devResults: devResults,
            rules: {
                type: [{ required: true, message: '请选择巡查类型', trigger: 'change' }],
                highwayCode: [{ required: true, message: '请选择公路名称', trigger: 'change' }],
                defectDiseaseType: [{ required: true, message: '请选择缺陷病害类型', trigger: 'change' }],
                direction: [{ required: true, message: '请选择公路方向', trigger: 'change' }],
                deptId: [{ required: true, message: '请选择巡查部门', trigger: 'change' }],
                inspectDate: [{ required: true, message: '请选择巡查日期', trigger: 'change' }],
                inspectTime: [{ required: true, message: '请选择巡查时段', trigger: 'change' }],
                principal: [{ required: true, message: '请选择负责人', trigger: 'change' }],
                inspectUsers: [{ required: true, message: '请选择巡查人员', trigger: 'change' }],
                locationType: [{ required: true, message: '请选择位置类型', trigger: 'change' }],
                facilityCode: [{ required: true, message: '请选择缺陷位置', trigger: 'change' }],
                stake1: [{ required: true, message: '请输入桩号', trigger: 'blur' }],
                deviceInfo: [{ required: true, message: '请选择设备' }],
                checkSituation: [{ required: true, message: '请输入检查情况', trigger: 'blur' }],
                abnormalDescription: [{ required: true, message: '请输入异常描述', trigger: 'blur' }],
                startStakeNo1: [{ required: true, message: '请输入桩号范围', trigger: 'blur' }]
            },
            form: {
                deptId: [],
                inspectUsers: [],
                deviceInfo: [],
                startStake1: '',
                endStake1: '',
                startStake2: '',
                endStake2: '',
                stake1: '',
                stake2: ''
            },
            deviceDialogVisible: false,
            currentIndex: 0,
            columns: Object.freeze([
                {
                    attrs: {
                        type: 'selection'
                    }
                },
                {
                    attrs: {
                        prop: 'stake',
                        label: '设备桩号',
                        'show-overflow-tooltip': true,
                        width: '200'
                    }
                },
                {
                    attrs: {
                        prop: 'name',
                        label: '设备名称',
                        'min-width': '140',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'deviceTypeName',
                        label: '设备类型',
                        'min-width': '140',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'belongPlace',
                        label: '所属位置',
                        'min-width': '140',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'result',
                    attrs: {
                        label: '巡检结果',
                        'min-width': '160'
                    }
                },
                {
                    slot: 'remake',
                    attrs: {
                        label: '异常描述',
                        'min-width': '160'
                    }
                },
                {
                    slot: 'handle',
                    attrs: {
                        label: '操作',
                        width: '120',
                        fixed: 'right'
                    }
                }
            ]),
            deviceList: [],
            selectedList: [],
            submitLoading: false
        }
    },
    methods: {
        locationTypeChange() {
            this.$refs['refForm'].clearValidate()
        },
        addDeviceInfo() {
            if (!this.form.highwayCode) {
                this.$alert('请先选择公路名称', '提示', {
                    confirmButtonText: '确定'
                })
                return
            }
            this.deviceDialogVisible = true
        },
        beforeSubmit() {
            let data = {}
            data = {
                ...this.form,
                deptId: this.form.deptId.join(','), // 部门
                inspectUsers: this.form.inspectUsers.join(','), // 巡查人员
                facilityCode: this.form.facilityCode && this.form.facilityCode.length >= 2 ? this.form.facilityCode[1] : '' // 设施id，获取到数据，取最后一级
            }
            if (this.form.locationType === 1) {
                data.lngLat = this.form.lngLatList.toString()
            }
            // 图片
            const photos = this.$refs['baseInfo'].photos
            if (this.form.type === 1 || this.form.type === 2) {
                if (photos && photos.length > 0) {
                    data.photosArray = photos.map(item => {
                        return {
                            picName: item.name,
                            url: item.response.data.objectUrl,
                            picDesc: item.picDesc
                        }
                    })
                } else {
                    data.photosArray = []
                }
            } else {
                if (photos && photos.length) {
                    const urls = photos.map((item) => {
                        return item.response.data.objectUrl
                    })
                    data.photos = urls.join(',')
                } else {
                    data.photos = ''
                }
            }

            // 巡查时段
            if (this.form.inspectTime && this.form.inspectTime.length) {
                data.inspectTime = this.form.inspectTime[0] + '~' + this.form.inspectTime[1]
            } else {
                data.inspectTime = ''
            }
            // 桩号
            if (this.form.stake1 && this.form.stake2) {
                data.stake = `K${this.form.stake1}+${this.form.stake2}`
            } else {
                data.stake = ''
            }
            return data
        },
        validDev() {
            for (let i = 0; i < this.form.deviceInfo.length; i++) {
                if (!this.form.deviceInfo[i].inspectionResult) {
                    this.$alert(`请选择设备${this.form.deviceInfo[i].name}的巡检结果`, '提示', {
                        confirmButtonText: '确定'
                    })
                    return false
                }
            }
            return true
        },
        submit() {
            const data = this.beforeSubmit()
            console.log(data)
            const isDevValid = this.validDev()
            this.$refs['refForm'].validate(async (valid) => {
                if (valid && isDevValid) {
                    this.submitLoading = true
                    this.model
                        .saveOrUpdate({ ...data })
                        .then(() => {
                            useSuccess({ message: '新增成功', onlyTip: false, routeName: 'FlawList' })
                        })
                        .finally(() => {
                            this.submitLoading = false
                        })
                }
            })
        },
        handleSelectionChange(val) {
            this.selectedList = val
        },
        // 设施列表批量和单个删除
        handleDeleteDevice(row) {
            reconfirm({
                isPromise: false,
                callback: () => {
                    const selectedList = row ? [row] : this.selectedList
                    const deviceList = this.form.deviceInfo
                    this.form.deviceInfo = this.filterSeletedArray(selectedList, deviceList)
                }
            })
        },
        filterSeletedArray(selectedArr, arr, key = 'id') {
            selectedArr.forEach((item) => {
                arr = arr.filter((m) => m[key] !== item[key])
            })
            return arr
        },
        handleSelectDevice(index) {
            // 当前点击选择机电的数据下标
            this.currentIndex = index
            this.deviceDialogVisible = true
        },
        getDeviceList(value) {
            this.form.deviceInfo = value
            this.deviceListName = value.map((item) => item.name).join('；')
        }
    }
}
</script>
<style scoped lang='scss'>
.add {
    width: 100%;
}
</style>
